package cn.easy.mortgage.web;

import cn.easy.base.bean.PageBean;
import cn.easy.base.bean.common.AjaxResultBean;
import cn.easy.base.domain.User;
import cn.easy.base.service.AutoNoConfigService;
import cn.easy.base.service.UserService;
import cn.easy.base.web.BaseController;
import cn.easy.mortgage.domain.Channel;
import cn.easy.mortgage.service.ChannelService;
import cn.easy.mortgage.service.LoanRequestService;
import cn.easy.mortgage.utils.Constants;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author huangm
 */
@Controller
@RequestMapping("/channel")
public class ChannelController extends BaseController {
    @Autowired
    private ChannelService channelService;
    @Autowired
    private LoanRequestService loanRequestService;
    @Autowired
    private UserService userService;
    @Autowired
    private AutoNoConfigService autoNoConfigService;

    @RequestMapping("")
    String index(Model model, HttpServletRequest request) {
        return "channel/index";
    }

    @RequestMapping("/list")
    @ResponseBody
    Page<Channel> list(PageBean pageBean, HttpServletRequest request) {
        Map<String, Object> searchParams = searchParams(request);
        if (!hasPermission(Constants.REQUEST_SEARCH_GLOBAL)) {
            Channel channel = channelService.findByUserId(getCurrentUserId());
            searchParams.put("LLK_no", channel.getNo());
        }
        Page<Channel> page = channelService.search(searchParams, pageBean);
        setConfigFieldValues(page, Constants.CHANNEL_TYPE_KEY, "type");
        setFieldValues(page, Channel.class, "pid", new String[]{"name"});
        return page;
    }

    @RequestMapping(value = "/form", method = RequestMethod.GET)
    String formGet(@RequestParam(value = "id", required = false) String id, Model model, HttpServletRequest request) {
        if (isValidId(id)) {
            Channel channel = channelService.getOne(id);
            model.addAttribute("channel", channel);
        } else {
            Channel channel = new Channel();
            Channel channelDb = channelService.findByUserId(getCurrentUserId());
            if (channelDb != null) {
                channel.setPid(channelDb.getId());
                channel.setType(channelDb.getType());
            } else {
                channel.setType(Constants.CHANNEL_TYPE_DEFAULT);
            }
            model.addAttribute("channel", channel);
        }
        if (!hasPermission(Constants.REQUEST_SEARCH_GLOBAL)) {
            model.addAttribute("isParent", true);
        }
        return "channel/form";
    }

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    @ResponseBody
    AjaxResultBean formPost(Channel channel, HttpServletRequest request) {
        if (channel.isNew() || StringUtils.isBlank(channel.getUserId())) {
            if (channelService.findByCode(channel.getCode()) != null) {
                return toError("code重复");
            }
            User user = channelService.valueOf(channel);
            User userDb = userService.save(user);
            userService.saveReAuthRoles(userDb.getId(), Constants.CHANNEL_ROLE);
            channel.setUserId(userDb.getId());
        }
        channelService.save(channel);
        return toSuccess("保存成功");
    }

    @RequestMapping(value = "/getAutoCode", method = RequestMethod.GET)
    @ResponseBody
    AjaxResultBean getAutoCode(Model model, HttpServletRequest request) {
        String code = autoNoConfigService.getNoByCode(Constants.AUTO_CHANNEL_CODE, "");
        return toSuccess("获取成功", code);
    }

    @RequestMapping("/delete")
    @ResponseBody
    AjaxResultBean delete(@RequestParam(value = "id") String id) {
        if (loanRequestService.exists(id)) {
            return toError("存在关联贷款申请，无法删除");
        }
        Channel channel = channelService.getOne(id);
        if (userService.getOne(channel.getUserId()) != null) {
            userService.delete(channel.getUserId());
        }
        channelService.delete(id);
        return toSuccess("删除成功");
    }

    @RequestMapping("/view")
    String view(@RequestParam(value = "id") String id, Model model) {
        Channel channel = channelService.getOne(id);
        model.addAttribute("channel", channel);
        return "channel/view";
    }

    @RequestMapping("/qrCode")
    void qrCode(@RequestParam(value = "id") String id, @RequestParam(required = false) String type, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException, WxErrorException {
        Channel channel = channelService.getOne(id);

        String filePath = channelService.genQrCode(channel, type, request);

        toDownload(filePath, channel.getName() + ".png", response);
    }

    @RequestMapping("/treeList")
    @ResponseBody
    List<Channel> treeList(HttpServletRequest request, @RequestParam(value = "isParent", required = false) boolean isParent) {
        List<Channel> list = new ArrayList<>();
        if (!hasPermission(Constants.REQUEST_SEARCH_GLOBAL)) {
            Channel channel = channelService.findByUserId(getCurrentUserId());
            if (isParent) {
                list = channelService.findByNo(channel.getNo().substring(0, 4));
            } else {
                list = channelService.findByNoStartingWith(channel.getNo().substring(0, 4));
            }
        } else {
            if (isParent) {
                list = channelService.findByPid(Constants.CHANNEL_PARENT);
            } else {
                list = channelService.findByNo("%");
            }
        }
        return list;
    }

}


